package com.xxx.multids;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据源切换器
 */
@Aspect
@Component
public class DataSourceSwitcher {

	private static final Logger log = LoggerFactory.getLogger(DataSourceSwitcher.class);

    @Pointcut("@within(com.xxx.multids.DynamicSwitchDataSource)||@annotation(com.xxx.multids.DynamicSwitchDataSource)")
    public void pointcut() {
    	
    }

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //方法注释当前注解
        DynamicSwitchDataSource annotationClass = method.getAnnotation(DynamicSwitchDataSource.class);
        if (annotationClass == null) {
            //类注释当前注解
            annotationClass = joinPoint.getTarget().getClass().getAnnotation(DynamicSwitchDataSource.class);
            if (annotationClass == null) {
                return;
            }
        }
        Object[] paramValues = joinPoint.getArgs();
        Integer orgId = null;
        for (Object paramValue : paramValues) {
        	//是否存在orgId
            if (paramValue instanceof Integer) {
            	orgId = (Integer) paramValue;
            }
        }

        /**
         * 根据orgId切换数据源
         */
        if (orgId!=null) {
            log.info("[DynamicDataSource]当前OrgId: " + orgId + ",开始切换数据源");
            DataSourceHandler.putDataSource(orgId);
        }
    }

    @After("pointcut()")
    public void after(JoinPoint point) {
        log.info("[DynamicDataSource]开始恢复数据源到默认");
        DataSourceHandler.clear();
    }

}
